package com.breakfast.fun.ui.user.pay;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.breakfast.fun.Constant;
import com.breakfast.fun.R;
import com.breakfast.fun.base.BaseActivity;
import com.breakfast.fun.data.entity.user.recharge.CmbPay;
import com.breakfast.fun.data.entity.user.recharge.PayBean;
import com.breakfast.fun.data.entity.user.recharge.PayResult;
import com.breakfast.fun.data.entity.user.recharge.WeiPay;
import com.breakfast.fun.event.WxEvent;
import com.breakfast.fun.ui.web.CmbPayActivity;
import com.breakfast.fun.util.L;
import com.breakfast.fun.util.T;
import com.breakfast.fun.view.widget.TitleBarView;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.unionpay.UPPayAssistEx;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;

import butterknife.Bind;

public class CouponShareActivity extends BaseActivity<BFPayPresenter, BFPayModel> implements BFPayContract.View {


    @Bind(R.id.tbv_bfpay)
    TitleBarView mTbvBfpay;
    @Bind(R.id.tv_order_pay_msg)
    TextView mTvOrderPayMsg;
    @Bind(R.id.ll_order_pay_msg)
    LinearLayout mLlOrderPayMsg;
    @Bind(R.id.tv_bfpay_orderno)
    TextView mTvBfpayOrderno;
    @Bind(R.id.tv_bfpay_price)
    TextView mTvBfpayPrice;
    @Bind(R.id.tv_bfpay_free)
    TextView mTvBfpayFree;
    @Bind(R.id.tv_bfpay_balance)
    TextView mTvBfpayBalance;
    @Bind(R.id.tv_bfpay_need_price)
    TextView mTvBfpayNeedPrice;
    @Bind(R.id.rb_bfpay_balance)
    RadioButton mRbBfpayBalance;
    @Bind(R.id.rb_bfpay_cmbkb)
    RadioButton mRbBfpayCmbkb;
    @Bind(R.id.rb_bfpay_ali)
    RadioButton mRbBfpayAli;
    @Bind(R.id.rb_bfpay_wx)
    RadioButton mRbBfpayWx;
    @Bind(R.id.rb_bfpay_cup)
    RadioButton mRbBfpayCup;
    @Bind(R.id.rg_bfpay_way)
    RadioGroup mRgBfpayWay;
    @Bind(R.id.btn_bfpay_submit)
    Button mBtnBfpaySubmit;
    @Bind(R.id.tv_bfpay_tip)
    TextView mTvBfpayTip;

    private final static int PAY_BALANCE = 1;
    private final static int PAY_ALI = 2;
    private final static int PAY_WX = 3;
    private final static int PAY_CMB = 4;
    private final static int PAY_CUP = 5;

    //银联在线支付
    public static final int PLUGIN_VALID = 0;
    public static final int PLUGIN_NOT_INSTALLED = -1;
    public static final int PLUGIN_NEED_UPGRADE = 2;
    // * mMode参数解释： "00" - 启动银联正式环境 "01" - 连接银联测试环境
    private String tnStr = "";
    private final static String mode = "00";

    private int payType = 1;

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_CHECK_FLAG = 2;

    SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("HH");
    private PayBean payBean;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    String resultStatus = payResult.getResultStatus();
                    if (TextUtils.equals(resultStatus, "9000")) {

                        T.show("支付成功!!");
                        showPaySuccess();
                    } else {
                        if (TextUtils.equals(resultStatus, "8000")) {
                            T.show("支付结果确认中");
                        } else if (TextUtils.equals(resultStatus, "4000")) {
                            T.show("支付失败,请检查是否已安装支付宝客户端");
                        } else {
                            T.show("支付失败");
                        }
                    }
                    break;
                }
                case SDK_CHECK_FLAG: {
                    T.show("检查结果为:" + msg.obj);
                    break;
                }
                default:
                    break;
            }
        }

    };

    @Override
    public int getLayoutId() {
        return R.layout.activity_bfpay;
    }

    @Override
    public void initView() {

        EventBus.getDefault().register(this);
        mTbvBfpay.setTitleNoRight("订单支付");
        mTbvBfpay.setBack(this);

        payBean = (PayBean) getIntent().getSerializableExtra("payBean");
        mTvBfpayPrice.setText(payBean.getTotalPrice() + "");
        mTvBfpayOrderno.setText(payBean.getOrderNo());


        if (payBean.getCmbpay() == null) {
            mRbBfpayCmbkb.setVisibility(View.GONE);
        } else {
            if (payBean.getCmbpay().getTip() != null && !TextUtils.isEmpty(payBean.getCmbpay().getTip().trim())) {
                mRbBfpayCmbkb.setText("\t招行一网通支付\n\t" + payBean.getCmbpay().getTip());
            }
        }

        if (payBean.getWeiPay() == null) {
            mRbBfpayWx.setVisibility(View.GONE);
        }

        if (payBean.getAlipay() == null) {
            mRbBfpayAli.setVisibility(View.GONE);
        }

//        if(payBean.getUmspay() == null){
//            mRbBfpayUms.setVisibility(View.GONE);
//        }

        if (getIntent().getBooleanExtra("isFromMall", false)) {
            mTvBfpayTip.setText("需支付:");
            mTvBfpayNeedPrice.setText(sub(payBean.getTotalPrice(), payBean.getFreePrice()) + "");
            payType = PAY_CMB;
            mRbBfpayBalance.setVisibility(View.GONE);
            mRbBfpayCmbkb.setChecked(true);
        } else {

            if (payBean.getAccountMoney() < sub(payBean.getTotalPrice(), payBean.getFreePrice())) {
                mTvBfpayTip.setText("还需支付:");
                mTvBfpayNeedPrice.setText(sub(sub(payBean.getTotalPrice(), payBean.getFreePrice()),
                        payBean.getAccountMoney()) + "");
                mRbBfpayBalance.setVisibility(View.GONE);
                payType = PAY_CMB;
                mRbBfpayCmbkb.setChecked(true);
            } else {
                mTvBfpayTip.setText("需支付:");
                mTvBfpayNeedPrice.setText(sub(payBean.getTotalPrice(), payBean.getFreePrice()) + "");
                payType = PAY_BALANCE;
                mRbBfpayBalance.setChecked(true);
            }

            if (payBean.getAccountMoney() == 0) {
                mTvBfpayTip.setText("需支付:");
                mTvBfpayNeedPrice.setText(sub(payBean.getTotalPrice(), payBean.getFreePrice()) + "");
                payType = PAY_WX;
                mRbBfpayWx.setChecked(true);
            }
        }

        mTvBfpayBalance.setText(payBean.getAccountMoney() + "");
        mTvBfpayFree.setText(payBean.getFreePrice() + "");
        if (!TextUtils.isEmpty(payBean.getAd())) {
            mLlOrderPayMsg.setVisibility(View.VISIBLE);
            mTvOrderPayMsg.setText(payBean.getAd());
        }

        mBtnBfpaySubmit.setOnClickListener(v -> {
            //10点后不能付款
            /*String time = mSimpleDateFormat.format(System.currentTimeMillis());

            if(Integer.parseInt(time) >= 22){
                T.show("请在晚上10点前付款噢！");
                return;
            }*/
            switch (payType) {
                case PAY_CMB:
                    payForCmb(payBean.getCmbpay());
                    break;
                case PAY_ALI:
                    payForAli(payBean.getAlipay());
                    break;
                case PAY_WX:
                    payForWx(payBean.getWeiPay());
                    break;
                case PAY_BALANCE:
                    presenter.payForBalance(payBean.getOrderNo());
                    break;
                case PAY_CUP:
                    //获得账单流水号
                    if (!TextUtils.isEmpty(payBean.getCuppay().getTn().trim())) {
                        payForCup(payBean.getCuppay().getTn());
                    } else {
                        T.show("获取订单流水号失败");
                    }
                    break;
            }
        });

        mRgBfpayWay.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_bfpay_balance:
                        payType = PAY_BALANCE;
                        break;
                    case R.id.rb_bfpay_ali:
                        payType = PAY_ALI;
                        break;
                    case R.id.rb_bfpay_cmbkb:
                        payType = PAY_CMB;
                        break;
                    case R.id.rb_bfpay_wx:
                        payType = PAY_WX;
                        break;
                    case R.id.rb_bfpay_cup:
                        payType = PAY_CUP;
                        break;
                }
            }
        });

    }

    private void payForWx(WeiPay pay) {
        final IWXAPI msgApi = WXAPIFactory.createWXAPI(context, null);
        msgApi.registerApp(Constant.WX_ID);

        PayReq payReq = new PayReq();
        payReq.appId = pay.getAppId();
        payReq.partnerId = pay.getPartnerId();
        payReq.prepayId = pay.getPrepayId();
        payReq.packageValue = "Sign=WXPay";
        payReq.nonceStr = pay.getNonceStr();
        payReq.timeStamp = pay.getTimeStamp();
        payReq.sign = pay.getSign();

        if (!msgApi.isWXAppInstalled()) {
            T.show("您还未安装微信,无法完成支付。");
            return;
        }

        msgApi.sendReq(payReq);
    }

    public void payForCmb(CmbPay cmbPay) {
        Intent intent = new Intent(this, CmbPayActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("cmbpay", cmbPay);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    private void payForAli(String aliPay) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask payTask = new PayTask(CouponShareActivity.this);
                // 调用支付接口，获取支付结果
                String result = payTask.pay(aliPay);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();

    }

    /**
     * 提供精确的减法运算。
     *
     * @param value1 被减数
     * @param value2 减数
     * @return 两个参数的差
     * //
     */
    public double sub(Number value1, Number value2) {
        BigDecimal b1 = new BigDecimal(Double.toString(value1.doubleValue()));
        BigDecimal b2 = new BigDecimal(Double.toString(value2.doubleValue()));
        return b1.subtract(b2).doubleValue();
    }


    @Override
    public void showPaySuccess() {
        T.show("支付成功");
        Intent intent = new Intent(CouponShareActivity.this, com.breakfast.fun.ui.user.coupon.CouponShareActivity.class);
        intent.putExtra("orderId",payBean.getOrderId() + "");
        intent.putExtra("orderNo",payBean.getOrderNo());


//        Intent intent = new Intent(BFPayActivity.this, UserOrderActivity.class);
//        intent.putExtra("isFromMall", getIntent().getBooleanExtra("isFromMall", false));

        startActivity(intent);
        this.finish();
    }

    public void payForCup(String tn) {

        int ret = UPPayAssistEx.startPay(this, null, null, tn, mode);
        if (ret == PLUGIN_NEED_UPGRADE || ret == PLUGIN_NOT_INSTALLED) {
            // 需要重新安装控件
            L.e(" plugin not found or need upgrade!!!");
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("提示");
            builder.setMessage("完成购买需要安装银联支付控件，是否安装？");

            builder.setNegativeButton("确定",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            UPPayAssistEx.installUPPayPlugin(CouponShareActivity.this);
                            dialog.dismiss();
                        }
                    });

            builder.setPositiveButton("取消",
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            builder.create().show();

        }
        L.e("" + ret);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        /*************************************************
         * 步骤3：处理银联手机支付控件返回的支付结果
         ************************************************/
        if (intent == null) {
            return;
        }

        String msg = "";
        /*
         * 支付控件返回字符串:success、fail、cancel 分别代表支付成功，支付失败，支付取消
         */
        String str = intent.getExtras().getString("pay_result");
        if (str.equalsIgnoreCase("success")) {
            // 支付成功后，extra中如果存在result_data，取出校验
            // result_data结构见c）result_data参数说明
            if (intent.hasExtra("result_data")) {
                String result = intent.getExtras().getString("result_data");

                try {
                    JSONObject resultJson = new JSONObject(result);
                    String sign = resultJson.getString("sign");
                    String data = resultJson.getString("data");
                    // 验签证书同后台验签证书
                    // 此处的verify，商户需送去商户后台做验签
//                    boolean ret = verify(data, sign, mode);
                    boolean ret = true;
                    if (ret) {
                        // 验证通过后，显示支付结果
                        msg = "后台验证通过，支付成功！";
                        showPaySuccess();
                    } else {
                        // 验证不通过后的处理
                        // 建议通过商户后台查询支付结果
                        msg = "后台验证不通过，支付失败！";
                    }
                } catch (JSONException e) {
                }
            } else {
                // 未收到签名信息
                // 建议通过商户后台查询支付结果
                msg = "未收到签名信息";
            }
        } else if (str.equalsIgnoreCase("fail")) {
            msg = "支付失败！";
        } else if (str.equalsIgnoreCase("cancel")) {
            msg = "用户取消了支付";
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("支付结果通知");
        builder.setMessage(msg);
        builder.setInverseBackgroundForced(true);
        // builder.setCustomTitle();
        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }


    @Subscribe
    public void onEventWx(WxEvent event) {
        if (event.getErrCode() == 0) {
            showPaySuccess();
        } else if (event.getErrCode() == 1) {
            T.show("支付失败");
        }
    }

    @Override
    protected void destroyView() {
        super.destroyView();
        EventBus.getDefault().unregister(this);
    }
}
